const resultConstant = {
    success: 1,
    error: 0,
    loginError: 2,
    date: 'date',
    code: 'code',
    msg: 'msg',
    tokenError: 'token非法'
};

const storageKey = {
    doQuestionData: 'do_question_data',
    addQuestionData: 'add_question_data',
    myQuestionData: 'my_question_data',
    allQuestionData: 'all_question_data',
    noteManageData: 'note_manage_data',
    categoryManageData: 'category_manage_data',
    meData: 'me_data',
}

// 本地调试时，使用本地地址
const prefixUrl = '/api';
// const prefixUrl = 'http://localhost:8088';
// const prefixUrl = 'https://climbing-ewe-adjusted.ngrok-free.app/question';

const gatewayPrefix = {
    question: '/question',
    user: '/user',
    note: '/note',
    category: '/category'
}

const localStorageKey = {
    token: 'token',
    userInfo: 'userInfo'
};

const questionKind = {
    choice: 0,
    blank: 1,
    judge: 2,
    solve: 3
};

const openStatus = {
    open: 1,
    notOpen: 0,
    yes: '是',
    no: '否'
};

optoins = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'];

const msgConstant = {
    deleteConfirm: '此操作将永久删除该项, 是否继续?',
    noQuestion: '没有题目',
    cancelDelete: '已取消删除',
    deleteSuccess: '删除成功'
}

const myColor = {
    blue: '#409EFF',
    default: '#DCDFE6',
}

const judge = {
    true: 0,
    false: 1,
    yes: '对',
    no: '错'
}

const split = {
    comma: ',',
    dot: '.',
    default: '|*|'
}

/*function handleError(_this, code, msg) {
    if (code === resultConstant.success) {
        return true;
    }
    console.log("code=" + code + ",msg=" + msg);
    _this.$alert(msg, '提示', {
            confirmButtonText: '确定',
            callback: action => {
                if (code === resultConstant.loginError) {
                    const preUrl = window.location.href;
                    // 跳转登录页面
                    window.location.href = prefixUrl + '/pages/login.html?preUrl=' + preUrl;

                    return false;
                }
            }
        }
    );
}*/

function showErrorAlert(_this, msg) {
    _this.$alert(msg, '提示', {
        confirmButtonText: '确定',
        callback: action => {
        },
    });
}

function showAlert(_this, msg) {
    _this.$alert(msg, '提示', {
        confirmButtonText: '确定',
        callback: action => {
        },
    });
}

function showConfirmAlert(_this, msg, ok, cancel) {
    _this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        ok();
    }).catch(() => {
        cancel();
    });
}

function showMsg(_this, msg) {
    _this.$message(msg);
}

function showSuccessMsg(_this, msg) {
    _this.$message({
        message: msg,
        type: 'success'
    });
}

function showWarningMsg(_this, msg) {
    _this.$message({
        message: msg,
        type: 'warning'
    });
}

function showErrorMsg(_this, msg) {
    _this.$message.error(msg);
}

function saveSessionStorage(_this, key, initData) {
    // 保存当前数据到sessionStorage
    // 在页面加载时读取sessionStorage里的状态信息
    let dataString = sessionStorage.getItem(key);
    let data = JSON.parse(dataString);
    if (data) {
        // 有数据直接获取
        Object.assign(_this.$data, data)
    } else {
        // 没有数据初始化数据
        initData();
    }

    // 在页面刷新时将数据保存到sessionStorage里
    window.addEventListener('beforeunload', () => {
        sessionStorage.setItem(key, JSON.stringify(_this.$data));
    })
}

function goMain() {
    window.location.href = 'main.html';
}

function back() {
    history.back()
}

// 获取我的所有分类 id,name,status,open,creator
function getMyCategories(finallyMethod) {
    const url = prefixUrl + gatewayPrefix.question + "/user/categories";
    return axios.get(url).then((resp) => {
        const result = resp.data;
        // console.log("getMyCategories:categories=" + JSON.stringify(result.data));
        return result.data;
    }).catch((error) => {
        console.error("Error fetching categories:", error);
    }).finally(() => {
        finallyMethod();
    });
}

// 通过JSON实现深拷贝
function copyByJSON(originalObj) {
    return JSON.parse(JSON.stringify(originalObj));
}

// 添加请求头
axios.defaults.headers.common['token'] = `${localStorage.getItem(localStorageKey.token)}`;

const userInfo = JSON.parse(localStorage.getItem(localStorageKey.userInfo));

// 未登录跳转
axios.interceptors.response.use((resp) => {
    const result = resp.data;
    // console.log("result=" + JSON.stringify(result));
    if (result.code === resultConstant.loginError) {
        const preUrl = window.location.href;
        // 跳转登录页面
        // window.location.href = prefixUrl + '/pages/user/login.html?preUrl=' + preUrl;
        window.location.href = 'login.html?preUrl=' + preUrl;
        // 清空Session storage
        sessionStorage.clear();
    }
    return resp;
});